package com.ljn.data.utils;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.util.StringUtils;

public class HostUtils {
    public HostUtils() {
    }

    public static String getResponseText(String url) {
        return getResponseText(url, "UTF-8");
    }

    public static String getResponseText(String url, String charset) {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        HttpMethodParams methodParams = method.getParams();
        methodParams.setParameter("http.useragent", "-");
        methodParams.setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler());
        InputStream in = null;
        BufferedReader reader = null;

        try {
            int statusCode = client.executeMethod(method);
            if (statusCode == 200) {
                in = method.getResponseBodyAsStream();
                reader = new BufferedReader(new InputStreamReader(in, charset));
                StringBuffer buf = new StringBuffer(128);

                String str;
                while((str = reader.readLine()) != null) {
                    buf.append(str);
                }

                String var10 = buf.toString();
                return var10;
            }
        } catch (Exception var21) {
            var21.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException var20) {
                var20.printStackTrace();
            }

            method.releaseConnection();
        }

        return "";
    }

    public static String getRemoteIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (!StringUtils.isEmpty(ip)) {
            int i = ip.indexOf(",");
            if (i != -1) {
                ip = ip.substring(0, i);
            }
        }

        return ip;
    }
}
